import { defineStore } from 'pinia'
import { CategoryItem, TopCategory, SubCategory } from '@/types/data'
import { getCategory, getTopCategory, getSubCategory } from "@/api/category"
import { topCategory } from '../constants'

const defaultCategory = topCategory.map(item => {
  return {
    name: item,
  }
})

export default defineStore('category', {
  state: () => ({
    list: defaultCategory as CategoryItem[],
    topCategory: {} as TopCategory,
    subCategory: {} as SubCategory,
  }),
  actions: {
    async getAllCategory () {
      const res = await getCategory()
      // 1. 给每一个一级分类添加一个open属性，用于控制显示隐藏
      res.data.result.forEach((item) => {
        item.open = false
      })
      this.list = res.data.result
    },
    // 弹层显示
    show (id: string) {
      const res = this.list.find(item => item.id === id)
      res!.open = true
    },
    // 弹层隐藏
    hide (id: string) {
      const res = this.list.find(item => item.id === id)
      res!.open = false
    },

    async getTopCategoryList (id: string) {
      const res = await getTopCategory({ id })
      this.topCategory = res.data.result
    },

    async getSubCategoryList (id: string) {
      const res = await getSubCategory({ id })
      this.subCategory = res.data.result
    },
  },
})